﻿namespace FastCode.Middlewares
{
    public class TokenValidationMiddleware
    {
        private readonly RequestDelegate _next;

        public TokenValidationMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            string authHeader = context.Request.Headers["Authorization"];

            if (authHeader != null && authHeader.StartsWith("Bearer "))
            {
                var token = authHeader.Substring("Bearer ".Length).Trim();

                // 验证token
                if (IsValidToken(token))
                {
                    await _next(context);
                    return;
                }
            }

            // 如果token无效，返回401 Unauthorized
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("Unauthorized");
        }

        private bool IsValidToken(string token)
        {
            // 在这里添加你的token验证逻辑
            // 例如，你可以解析token，然后验证它的签名和有效期
            // 如果token有效，返回true；否则，返回false

            return false;
        }
    }
}
